package com.levi.distributedsession.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，拦截获取header里面的token，并且解析获取里面的值
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final String TOKEN = "token";
    public static final String JWT_KEY = "jwt";
    public static final String UID = "uid";
    public static final String USERNAME = "username";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token为空");
        }
        JWTVerifier verifier = null; //Reusable verifier instance
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_KEY);
            verifier = JWT.require(algorithm)
                    .withIssuer("auth0")
                    .build();
            //获取  payload  中的信息
            String uid =  verifier.verify(token).getClaim(UID).asString();
            String username = verifier.verify(token).getClaim(USERNAME).asString();
            request.setAttribute(UID,uid);
            request.setAttribute(USERNAME,username);
            //token过期排除异常
        } catch (TokenExpiredException e) {
            throw new RuntimeException("token过期");
            //解析失败抛出异常
        }catch (JWTDecodeException e){
            throw new RuntimeException("解码失败");
        }
        return true;
    }
}
